// ignore_for_file: deprecated_member_use

import 'package:flutter/material.dart';
import 'package:flutter_hplus/components/tables/widgets/h_data_column.dart';
import 'package:flutter_hplus/components/tables/h_data_table_controller.dart';
import 'package:flutter_hplus/components/tables/widgets/h_data_table_style.dart';
import 'package:flutter_hplus/components/tables/widgets/table_actions.dart';
import 'package:flutter_hplus/components/tables/widgets/table_content.dart';
import 'package:flutter_hplus/components/tables/widgets/table_pagination.dart';
import 'package:flutter_hplus/theme/theme.dart';

/// 数据表格组件
/// 
/// 提供与H+ UI框架一致的数据表格功能，包括：
/// - 分页功能
/// - 搜索过滤
/// - 排序功能
/// - 悬停效果
/// - 条纹样式
class HDataTable extends StatefulWidget {
  /// 表格列定义
  final List<HDataColumn> columns;
  
  /// 表格数据
  final List<Map<String, dynamic>> data;
  
  /// 是否显示边框
  final bool showBorder;
  
  /// 是否显示条纹
  final bool showStripes;
  
  /// 是否显示悬停效果
  final bool showHover;
  
  /// 是否启用分页
  final bool enablePagination;
  
  /// 每页显示的行数选项
  final List<int> rowsPerPageOptions;
  
  /// 默认每页显示的行数
  final int defaultRowsPerPage;
  
  /// 是否启用搜索
  final bool enableSearch;
  
  /// 自定义表格样式
  final HDataTableStyle? style;
  
  /// 表格头部左侧操作按钮
  final List<Widget>? leftActions;
  
  /// 表格头部右侧操作按钮（搜索框旁边）
  final List<Widget>? rightActions;
    
  /// 行点击回调
  final Function(Map<String, dynamic>)? onRowTap;

  /// 构造函数
  const HDataTable({
    super.key,
    required this.columns,
    required this.data,
    this.showBorder = true,
    this.showStripes = true,
    this.showHover = true,
    this.enablePagination = true,
    this.rowsPerPageOptions = const [10, 25, 50, 100],
    this.defaultRowsPerPage = 10,
    this.enableSearch = true,
    this.style,
    this.leftActions,
    this.rightActions,
    this.onRowTap,
  });

  @override
  State<HDataTable> createState() => _HDataTableState();
}

class _HDataTableState extends State<HDataTable> {
  late HDataTableController _tableController;
  double _lastCalculatedWidth = 0;

  @override
  void initState() {
    super.initState();
    _tableController = HDataTableController(
      defaultRowsPerPage: widget.defaultRowsPerPage,
      data: widget.data,
      columnsCount: widget.columns.length,
    );
  }
  
  @override
  void didUpdateWidget(HDataTable oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 如果数据或列发生变化，更新控制器
    if (oldWidget.data != widget.data) {
      _tableController.updateData(widget.data);
    }
    
    if (oldWidget.columns.length != widget.columns.length) {
      _tableController.updateColumnsCount(widget.columns.length);
    }
  }
  
  @override
  void dispose() {
    _tableController.dispose();
    super.dispose();
  }

  /// 处理列宽变化
  void _handleColumnWidthsChanged(List<double> newWidths) {
    // 更新控制器中的列宽数据
    for (int i = 0; i < newWidths.length; i++) {
      if (i < _tableController.columnWidths.length) {
        _tableController.columnWidths[i] = newWidths[i];
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final theme = HTheme.of(context);
    
    return AnimatedBuilder(
      animation: _tableController,
      builder: (context, _) {
        return LayoutBuilder(
          builder: (context, constraints) {
            final availableWidth = constraints.maxWidth;
            
            // 如果可用宽度变化，重新计算列宽
            if (_lastCalculatedWidth != availableWidth) {
              _lastCalculatedWidth = availableWidth;
              // 延迟执行，确保布局完成后再计算
              WidgetsBinding.instance.addPostFrameCallback((_) {
                _tableController.calculateColumnWidths(widget.columns, availableWidth);
              });
            }
            
            return Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              mainAxisSize: MainAxisSize.max,
              children: [
                // 搜索和操作按钮
                if (widget.enableSearch || widget.leftActions != null || widget.rightActions != null)
                  TableActions(
                    searchController: _tableController.searchController,
                    onSearch: _tableController.handleSearch,
                    leftActions: widget.leftActions,
                    rightActions: widget.rightActions,
                    enableSearch: widget.enableSearch,
                  ),
                  
                // 表格内容
                Expanded(
                  child: Card(
                    margin: EdgeInsets.zero,
                    elevation: 1,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
                      side: widget.showBorder 
                          ? BorderSide(color: theme.colors.divider) 
                          : BorderSide.none,
                    ),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(theme.dimens.borderRadius),
                      child: TableContent(
                        columns: widget.columns,
                        data: _tableController.currentPageData,
                        columnWidths: _tableController.columnWidths,
                        hoveredRowIndex: _tableController.hoveredRowIndex,
                        showBorder: widget.showBorder,
                        showStripes: widget.showStripes,
                        showHover: widget.showHover,
                        onSort: (columnIndex) => _tableController.handleSort(columnIndex, widget.columns[columnIndex].field),
                        onColumnResize: (columnIndex, newWidth) {
                          _tableController.resizeColumn(columnIndex, newWidth);
                          // 当一列宽度调整后，重新计算其他列宽度
                          _tableController.calculateColumnWidths(widget.columns, availableWidth);
                        },
                        onColumnReset: (columnIndex) {
                          _tableController.resetColumnWidth(columnIndex);
                          // 重置列宽后，重新计算所有列宽度
                          _tableController.calculateColumnWidths(widget.columns, availableWidth);
                        },
                        onHoverRow: _tableController.setHoveredRow,
                        onRowTap: widget.onRowTap,
                        sortColumnIndex: _tableController.sortColumnIndex,
                        sortAscending: _tableController.sortAscending,
                        onColumnWidthsChanged: _handleColumnWidthsChanged,
                      ),
                    ),
                  ),
                ),
                
                // 分页控件
                if (widget.enablePagination)
                  TablePagination(
                    currentPage: _tableController.currentPage,
                    totalPages: _tableController.totalPages,
                    rowsPerPage: _tableController.rowsPerPage,
                    totalItems: _tableController.filteredData.length,
                    rowsPerPageOptions: widget.rowsPerPageOptions,
                    onPageChanged: _tableController.handlePageChange,
                    onRowsPerPageChanged: _tableController.handleRowsPerPageChange,
                  ),
              ],
            );
          }
        );
      },
    );
  }
} 